package bubbleFishBob.utilities;

import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import com.golden.gamedev.Game;

public class FileReader {

    private Scanner myScanner;
    private File myFile;
    private Game myGame;
    
    public FileReader(Game game, File file)
    {
        myFile = file;
        myGame = game;
    }
    
    /**
     * Reads in points representing the path of the bubbles.
     * Creates Points with specified coordinates
     * Points have been transformed from original because of strange variables
     * @return List of points representing path
     */
    public List<Point> readPathPoints()
    {
        List<Point> pointList = new ArrayList<Point>();
        for(String str: this.readTag("<Points>"))
        {
            String[] points = str.split(",");
            pointList.add(new Point(Integer.parseInt(points[0]), Integer.parseInt(points[1])));
        }

        return pointList;
    }
    
    /**
     * Initializes/Resets scanner
     */
    private void initializeScanner()
    {
        try {
            myScanner = new Scanner(myFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * Reads the number of bubbles to use from tag
     * @return total number of bubbles to use
     */
    public int readNumBubbles()
    {
        List<String> result = this.readTag("<NumBubbles>");
        return (result.size() == 1) ? (Integer.parseInt(result.get(0))) : -1;
    }
    
    /**
     * Reads in bubblesimages tag
     * @return list of BufferedImage representing bubbleimages
     */
    public List<BufferedImage> readBubbleImages()
    {
        List<BufferedImage> bubbleImages = new ArrayList<BufferedImage>();
        for(String str: this.readTag("BubbleImages>"))
        {
            bubbleImages.add(myGame.getImage(str));
        }
        
        return bubbleImages;
    }
    
    /**
     * Reads in GameObjects tag
     * @return List of strings representing gameobjects
     */
    public List<String> readGameObjects()
    {

        return this.readTag("<GameObjects>");
    }
    
    /**
     * Reads in data from specified tag
     * @param tag
     * @return list of strings representing data in tag
     */
    public List<String> readTag(String tag)
    {
        List<String> data = new ArrayList<String>();
        String endTag = tag.charAt(0) + "/" + tag.substring(1);
        
        this.initializeScanner();
        while(myScanner.hasNextLine())
        {
            if(myScanner.nextLine().equals((tag)))
            {
                String line = myScanner.nextLine();
                while(!line.equals(endTag))
                {
                    data.add(line);
                }
            }
        }
        return (data.size() > 0) ? data : null;
    }

}
